namespace Ultimate.Team.Controls
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;
		
	using Ultimate.DAL.CollectionClasses;
	using Ultimate.DAL;
	using Ultimate.DAL.HelperClasses;
	using Ultimate.DAL.EntityClasses;
	using Ultimate.DAL.FactoryClasses;
	using SD.LLBLGen.Pro.ORMSupportClasses;

	/// <summary>
	///		This control is used by captains or admins to edit there teams.
	///		Regular users can view the team.
	///		Captains can view the team, edit the name and remove players
	///		Admins can view the team, view and edit admin details relating to payment as well as add and remove players.
	/// </summary>
	public class EditTeam : System.Web.UI.UserControl
	{
		protected System.Web.UI.WebControls.TextBox teamName;
		protected System.Web.UI.WebControls.TextBox leagueName;
		protected System.Web.UI.WebControls.CheckBox Paid;
		protected System.Web.UI.WebControls.Label PaidDate;
		protected System.Web.UI.WebControls.Panel extraInfo;
		protected System.Web.UI.WebControls.DropDownList LeagueID;
		protected System.Web.UI.WebControls.Button btnSaveTeam;
		protected System.Web.UI.WebControls.TextBox TeamFee;
		protected System.Web.UI.WebControls.DataGrid dgPlayers;
		protected System.Web.UI.WebControls.DataGrid dgAvailablePlayers;
		protected System.Web.UI.WebControls.Literal h2;
		protected System.Web.UI.WebControls.Literal AmountDue;

        protected System.Web.UI.WebControls.LinkButton  btnCloseTeam;
        protected System.Web.UI.WebControls.HyperLink EmailTeam;
        protected System.Web.UI.WebControls.DataGrid  Report;
        protected System.Web.UI.WebControls.TextBox AmountPaid;
        protected System.Web.UI.WebControls.Panel AvailablePlayers_Panel;

		
		
        
        DAL.EntityClasses.TeamEntity team;
		public int TeamID
		{
			get
			{
				return Convert.ToInt32(ViewState["TeamID"]);
			}
			set
			{
				ViewState["TeamID"] = value;
			}
		}
		/// <summary>
		/// On page load we determin the role of the user accessing the page (Admin,Captain,Regular)
		/// Depending on the role the visibility of various controls is changed.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Page_Load(object sender, System.EventArgs e)
		{
			if (!this.IsPostBack )
			{
				TeamID=-1;
				if (Request.QueryString["TeamID"] != null )
				{
					this.TeamID = Convert.ToInt32(Request.QueryString["TeamID"]);
				}
				ViewState["SortExpression"]="LastName";
				ViewState["SortOrder"]=SortOperator.Ascending;			
				BindData();
                if (team != null && 
                    CommunityServer.Components.CSContext.Current.User.IsInRoles(new string[] {team.League.RoleName}))
				{
					extraInfo.Visible=true;
					dgPlayers.Columns[1].Visible=true;
					dgPlayers.Columns[2].Visible=true;
					dgPlayers.Columns[3].Visible=true;
					dgPlayers.Columns[4].Visible=true;
					dgPlayers.Columns[5].Visible=true;
					dgPlayers.Columns[6].Visible=true;
					dgPlayers.Columns[7].Visible=true;
					dgPlayers.Columns[8].Visible=true;
                    AvailablePlayers_Panel.Visible = true;
					dgAvailablePlayers.Visible=true;
                    teamName.Enabled = true;
                    btnSaveTeam.Visible = true;
                    btnCloseTeam.Visible = true;
                    EmailTeam.Visible = true;
                    EmailTeam.NavigateUrl = this.ResolveUrl("~/admin/bulkemail.aspx?teamID=" + this.TeamID.ToString());
                    try
                    {
                        Report.DataSource = DAL.StoredProcedureCallerClasses.RetrievalProcedures.TeamReport(this.TeamID);
                    }
                    catch { }
                    Report.DataBind();
                    Report.Visible = true;
				}
				//check to see if they are the captain.
                PlayerEntity pe = new PlayerEntity();
                System.Web.Security.MembershipUser mu = System.Web.Security.Membership.GetUser();
                pe.FetchUsingUCUserID((Guid)mu.ProviderUserKey);
				TeamPlayerEntity tpe = new TeamPlayerEntity(this.TeamID,pe.UserID);
				if (tpe.RoleID==(int)Roles.Captain)
				{
                    dgPlayers.Columns[1].Visible = true;
                    dgPlayers.Columns[7].Visible = true;
                    teamName.Enabled = true;
                    btnSaveTeam.Visible = true;
                    btnCloseTeam.Visible = true;
                    EmailTeam.Visible = true;
                    EmailTeam.NavigateUrl = this.ResolveUrl("~/admin/bulkemail.aspx?teamID=" + this.TeamID.ToString());
				}
				else if(tpe.RoleID==(int)Roles.Player)
				{
					dgPlayers.Columns[1].Visible=true;
				}
                string script = "<script language=JavaScript>\n";
                script += "function IncrementPaid()\n{\n";
                //				script +="alert(parseInt(document.getElementById('"+AmountPaid.ClientID+"').value) );";
                script += "document.getElementById('" + AmountPaid.ClientID + "').value = parseInt(document.getElementById('" + AmountPaid.ClientID + "').value) +parseInt(document.getElementById('AddMoney').value);\n";
                script += "}\n";
                script += "</script>";
                Page.RegisterClientScriptBlock("sdf", script);
			}
			
		}

		/// <summary>
		/// Autobind binds the details.
		/// Datagrids are bound manually.
		/// </summary>
		private void BindData()
		{
			LeagueCollection lc = new LeagueCollection();
			PredicateExpression A = new PredicateExpression();
			lc.GetMulti(null);
			LeagueID.DataSource=lc.Items;
			LeagueID.DataTextField="Name";
			LeagueID.DataValueField="LeagueID";
			LeagueID.DataBind();

			if (TeamID != -1)
			{
                
				team = new TeamEntity(TeamID);
				Ultimate.AutoBind.BindObjectToControls(team,this);
				h2.Text=team.TeamName;
				PaidDate.Text=team.PaidDate.ToShortDateString();
				if (team.TestOriginalFieldValueForNull(TeamFieldIndex.PaidDate))PaidDate.Text="";
				
                BindPlayers();
				BindAvailablePlayers();
				
				decimal tmp = team.League.TeamFee+(team.League.PlayerFee*team.PlayerCollectionViaTeamPlayer.Count);
				
				AmountDue.Text = String.Format("{0:c}",tmp)+" ("+String.Format("{0:c}",team.League.TeamFee)+" + ("+String.Format("{0:c}",team.League.PlayerFee)+" * "+team.PlayerCollectionViaTeamPlayer.Count.ToString()+"))";
                if (team.Closed == true) btnCloseTeam.Text = "Open Team";
                else btnCloseTeam.Text = "Close Team";
			}
		}

		/// <summary>
		/// Binds the dgPlayers datagrid
		/// </summary>
		private void BindPlayers()
		{
            DAL.TypedListClasses.TeamPlayerUserTypedList tpu = new Ultimate.DAL.TypedListClasses.TeamPlayerUserTypedList();
            PredicateExpression A = new PredicateExpression();
            A.Add(PredicateFactory.CompareValue(TeamFieldIndex.TeamID, ComparisonOperator.Equal, this.TeamID ));
            ISortExpression sorter = new SortExpression(SortClauseFactory.Create(PlayerFieldIndex.LastName, SortOperator.Ascending));
            tpu.Fill(0, sorter, false, A);
            //DAL.EntityClasses.TeamEntity te = new TeamEntity(TeamID);
            dgPlayers.DataSource = tpu.Rows;
			dgPlayers.DataBind();
			
		}

		/// <summary>
		/// Binds the dgAvailablePlayers datagrid
		/// Calls BindAvailablePlayers(PlayerFieldIndex sortExpression,SortOperator sort) with the values found in the viewstate
		/// </summary>
		private void BindAvailablePlayers()
		{
			SortOperator s ;
			if (ViewState["SortOrder"].ToString() == SortOperator.Ascending.ToString()) s = SortOperator.Ascending;
			else s = SortOperator.Descending;
			switch(ViewState["SortExpression"].ToString())
			{
				case "LastName":
					BindAvailablePlayers(PlayerFieldIndex.LastName,s);
					break;
				case "SkillLevel":
					BindAvailablePlayers(PlayerFieldIndex.SkillLevel,s);
					break;
				case "Gender":
					BindAvailablePlayers(PlayerFieldIndex.Male,s);
					break;
			}		
			
		}

		/// <summary>
		/// Binds the dgAvailablePlayers datagrid
		/// Sorts the datagrid bassed on the parameters
		/// </summary>
		/// <param name="sortExpression">The names of the database field to be sorted on</param>
		/// <param name="sort">Either asc or desc</param>
		private void BindAvailablePlayers(PlayerFieldIndex sortExpression,SortOperator sort)
		{
            DAL.TypedListClasses.TeamPlayerUserTypedList tpu = new Ultimate.DAL.TypedListClasses.TeamPlayerUserTypedList();
            PredicateExpression A = new PredicateExpression();
			IRelationCollection relations = new RelationCollection();

			relations.Add(PlayerEntity.Relations.TeamPlayerEntityUsingUserID);
			int individualTeamID = GetIndivudalsTeamID();
			
			
			A.Add(PredicateFactory.CompareValue(TeamPlayerFieldIndex.TeamID , ComparisonOperator.Equal, individualTeamID));
			
			ISortExpression sorter = new SortExpression(SortClauseFactory.Create(sortExpression, sort));
            tpu.Fill(0, sorter, false, A);
			//tc.GetMulti(A,10000,sorter,relations);

            dgAvailablePlayers.DataSource = tpu.Rows;
			dgAvailablePlayers.DataBind();
		}

		/// <summary>
		/// Used by the datafrid to convert the boolean "Male" to a text string.
		/// </summary>
		/// <param name="male">Boolean the is true for male and false for female</param>
		/// <returns></returns>
		protected string GetGender(object male)
		{
			if ((bool)male== true) return "Male";
			return "Female";
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="UserID"></param>
		/// <returns></returns>
		protected string GetWaiver(object UserID)
		{
            Guid userID = new Guid(UserID.ToString());
            TeamPlayerEntity tpe = new TeamPlayerEntity(this.TeamID,userID);
			
			
			if (tpe.WaiverSigned)
			{
				return "Yes";	
			}
			else
			{
				return "No";
			}
		}

        
		/// <summary>
		/// 
		/// </summary>
		/// <param name="PlayerID"></param>
		/// <returns></returns>
		protected string GetFriends(object UserID)
		{
            Guid userID = new Guid(UserID.ToString());
			TeamPlayerEntity tpe = new TeamPlayerEntity(GetIndivudalsTeamID(),userID);
			
			
			return(tpe.FriendsList);
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="UserID"></param>
		/// <returns></returns>
		protected string GetRole(object UserID)
		{

            Guid userID = new Guid(UserID.ToString());
			TeamPlayerEntity tpe = new TeamPlayerEntity(this.TeamID,userID);
			
			if (tpe.RoleID  ==(int)Roles.Captain)
			{
				return "C";	
			}
			else
			{
				return "P";
			}
		}

		/// <summary>
		/// Saves the teams details.
		/// If the team's paid status has changed to paid then it records todays date as the paiddate.
		/// 
		/// </summary>
		/// <param name="o"></param>
		/// <param name="e"></param>
		protected void SaveTeam(System.Object o, System.EventArgs e)
		{
			TeamEntity te ;
			bool paid=false;
			if (TeamID != -1)
			{
				te = new TeamEntity(TeamID);
				paid = te.Paid;
			}
			else
			{
				te = new TeamEntity();
			}
			if (Paid.Checked && !paid)te.PaidDate=DateTime.Now;
			
			AutoBind.BindControlsToObject(te,this);
			
			te.Save();

			this.TeamID = te.TeamID;
			BindData();
		}

		/// <summary>
		/// Removes a player from the team.  If there is an "Individuals" team in the league then the player is added to that.
		/// If not then the player is removed from the league.
		/// </summary>
		/// <param name="o"></param>
		/// <param name="e"></param>
		protected void RemovePlayer(System.Object o, DataGridCommandEventArgs e)
		{
			Guid userID = new Guid(dgPlayers.DataKeys[e.Item.DataSetIndex].ToString());
			TeamPlayerEntity tpe = new TeamPlayerEntity(this.TeamID,userID);
			
			int individualsTeamId = GetIndivudalsTeamID();
			if (individualsTeamId >0 && this.TeamID != individualsTeamId)
			{
				tpe.TeamID= individualsTeamId;
				tpe.RoleID= (int)Roles.Individual;				
				tpe.Save();
			}
			else
			{
				tpe.Delete();
			}
			BindData();		
//			BindPlayers();
//			BindAvailablePlayers();
		}

		protected void dgPlayers_OnItemCommand(System.Object o, DataGridCommandEventArgs e)
		{
			if (e.CommandName == "ToggleWaiver")
			{
                Guid userID = new Guid(dgPlayers.DataKeys[e.Item.DataSetIndex].ToString());
				TeamPlayerEntity tpe = new TeamPlayerEntity(this.TeamID,userID);
				tpe.WaiverSigned=!tpe.WaiverSigned;
				tpe.Save();
				BindPlayers();
			}
			
			if (e.CommandName == "ToggleCaptain")
			{
                Guid userID = new Guid(dgPlayers.DataKeys[e.Item.DataSetIndex].ToString());
				TeamPlayerEntity tpe = new TeamPlayerEntity(this.TeamID,userID);
				if (tpe.RoleID==(int)Roles.Player ) tpe.RoleID=(int)Roles.Captain;
				else tpe.RoleID=(int)Roles.Player;
				tpe.Save();
				BindPlayers();
			}
		}

		/// <summary>
		/// Adds a player from the dgAvailablePlayer datagrid to the team with a "player" role.
		/// 
		/// </summary>
		/// <param name="o"></param>
		/// <param name="e"></param>
		protected void AddPlayer(System.Object o, DataGridCommandEventArgs e)
		{
            Guid userID = new Guid(dgAvailablePlayers.DataKeys[e.Item.DataSetIndex].ToString());
			
			int individualsTeamId  = GetIndivudalsTeamID();
			TeamPlayerEntity tpe = new TeamPlayerEntity(individualsTeamId,userID);

			tpe.TeamID= TeamID;
			tpe.RoleID= (int)Roles.Player;
			tpe.Save();
			BindData();
//			BindPlayers();
//			BindAvailablePlayers();
			
		}

		/// <summary>
		/// Sorts the available players datagrid
		/// </summary>
		/// <param name="o"></param>
		/// <param name="e"></param>
		protected void dgAvailablePlayers_OnSortCommand(object o, DataGridSortCommandEventArgs e)
		{
			SortOperator s =SortOperator.Ascending;
			if (ViewState["SortExpression"].ToString() == e.SortExpression )
			{

				if (ViewState["SortOrder"].ToString() == SortOperator.Ascending.ToString()) s = SortOperator.Descending;
			}
			ViewState["SortExpression"] = e.SortExpression;
			ViewState["SortOrder"]=s.ToString();
			switch(e.SortExpression)
			{
				case "LastName":
					BindAvailablePlayers(PlayerFieldIndex.LastName,s);
					break;
				case "SkillLevel":
					BindAvailablePlayers(PlayerFieldIndex.SkillLevel,s);
					break;
				case "Gender":
					BindAvailablePlayers(PlayerFieldIndex.Male,s);
					break;
			}		
		}
		/// <summary>
		/// Handles the paging of the dgAvailablePlayers datagrid
		/// </summary>
		/// <param name="o"></param>
		/// <param name="e"></param>
		protected void dgAvailablePlayers_OnPageIndexChanged(object o,DataGridPageChangedEventArgs e)
		{
			dgAvailablePlayers.CurrentPageIndex=e.NewPageIndex;
			BindAvailablePlayers();
			
		}

		/// <summary>
		/// Gets the id of the "individuals" team for the current league or returns -1 if there is none
		/// </summary>
		/// <returns>Individuals team id or -1 if none</returns>
		protected int GetIndivudalsTeamID()
		{

			TeamCollection tc = new TeamCollection();
			PredicateExpression A = new PredicateExpression();
			A.Add(PredicateFactory.CompareValue(TeamFieldIndex.LeagueID , ComparisonOperator.Equal, Convert.ToInt32(this.LeagueID.SelectedValue) ));
			A.AddWithAnd(PredicateFactory.CompareValue(TeamFieldIndex.TeamName  , ComparisonOperator.Equal, "Individuals"));
			tc.GetMulti(A);
			if (tc.Count >0)
			{
				return (tc[0].TeamID);
			}
			else return -1;
		}

        protected void ShowAllAvailablePlayers(Object o, System.EventArgs e)
        {
            dgAvailablePlayers.AllowPaging = false;
            BindAvailablePlayers();
        }
        protected void CloseTeam(Object o, System.EventArgs e)
        {
            TeamEntity te = new TeamEntity(this.TeamID);
            if (te.Closed) te.Closed = false;
            else te.Closed = true;
            te.Save();
            BindData();
        }
		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion
	}
}
